package com.tegtech.tools.aliyun.support;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.geoip.model.v20200101.DescribeIpv4LocationRequest;
import com.aliyuncs.geoip.model.v20200101.DescribeIpv4LocationResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.tegtech.tools.aliyun.domain.Ipv4Location;
import com.tegtech.tools.aliyun.properties.AliyunProperties;

import lombok.extern.slf4j.Slf4j;

/**
 * ipv4地址解析
 * @Author Jun
 * @date 2020年12月25日 上午10:18:47
 */
@Slf4j
public class Ipv4Describe {
	
	// 地域
	private static final String REGIONID = "cn-hangzhou";
	// 语言
	private static final String LANG = "cn";

	/**
	 * 根据ipv4地址获取地理位置
	 * @param ip
	 * @return
	 */
	public static Ipv4Location getLocationByIpv4(String ip) {
		DefaultProfile profile = DefaultProfile.getProfile(REGIONID, AliyunProperties.getAccessId(), AliyunProperties.getAccessSecret());
		IAcsClient client = new DefaultAcsClient(profile);
		
		DescribeIpv4LocationRequest request = new DescribeIpv4LocationRequest();
		request.setIp(ip);
		request.setLang(LANG);
		
		try {
			DescribeIpv4LocationResponse response = client.getAcsResponse(request);
			return new Ipv4Location(response.getCountryCode(), response.getCountry(), response.getProvince(), response.getCity(), response.getCounty(), response.getIsp());
			
		} catch (Exception e) {
			log.error("根据ip查询地理位置出错，ERROR：{}", e);
		}
		return null;
	}
	
}
